package org.codefinger.json.parser.deserializer;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.codefinger.json.parser.JSONParser;
import org.codefinger.json.util.magic.MagicAttribute;
import org.codefinger.json.util.magic.MagicConstructor;
import org.codefinger.json.util.magic.MagicPojo;

public class PojoDeserializer {

	private Map<String, PojoFieldDeserializer>	fieldMap	= new HashMap<String, PojoFieldDeserializer>();

	private MagicConstructor<?>					constructor;

	public PojoDeserializer(Class<?> pojoClass) {

		MagicPojo<?> magicPojo = MagicPojo.getMagicPojo(pojoClass);
		Iterator<MagicAttribute> iterator = magicPojo.getMagicAttributes();
		MagicAttribute magicAttribute;
		while (iterator.hasNext()) {
			magicAttribute = iterator.next();
			fieldMap.put(magicAttribute.getFieldName(), new PojoFieldDeserializer(magicAttribute, JSONParser.getDeserializer(magicAttribute.getField().getGenericType())));
		}
		this.constructor = magicPojo.getConstructor();
	}

	public PojoFieldDeserializer getPojoFieldDeserializerCache(String fieldName) {
		return fieldMap.get(fieldName);
	}

	public Object newInstance() {
		return constructor.newInstance();
	}
}
